package com.um.jdy.common.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.um.jdy.common.system.code.SystemCode;
import com.um.jdy.common.system.dao.RoleDao;
import com.um.jdy.common.system.dao.UserDao;
import com.um.jdy.common.system.dao.UserRoleDao;
import com.um.jdy.common.system.entity.dto.UserDTO;
import com.um.jdy.common.system.entity.po.Menu;
import com.um.jdy.common.system.entity.po.User;
import com.um.jdy.common.system.entity.vo.MenuTreeNode;
import com.um.jdy.common.system.entity.vo.UserVO;
import com.um.jdy.common.system.service.UserService;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.helper.SessionHelper;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.service.TreeServiceImpl;
import com.um.springboot.starter.utils.DesEncrypter;
import com.um.springboot.starter.utils.JSONUtil;
import com.um.springboot.starter.utils.RSAUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 服务实现类：管理员用户表
 */
@Service
@Transactional
@Slf4j
public class UserServiceImpl extends TreeServiceImpl<UserDao, User, MenuTreeNode> implements UserService {

    @Autowired
    SessionHelper sessionHelper;

    @Autowired
    RoleDao roleDao;

    @Autowired
    UserRoleDao userRoleDao;

    /**
     * 查询用户登录资料
     *
     * @return
     */
    @Override
    public Response<UserVO> getUserInfo() {
        Map userInfo = sessionHelper.getSessionUser();
        if(userInfo == null){
            return Response.failed(SystemCode.LoginInvalid);
        }else{
            String json = JSONUtil.toJSONString(userInfo);
            UserVO userVO = JSON.parseObject(json,UserVO.class);
            return Response.success(userVO);
        }
    }

//    /**
//     * 读取用户角色的菜单
//     *
//     * @param userId
//     * @return
//     */
//    @Override
//    public Response<MenuTreeNode> getUserMenu(String userId) {
//        List<Menu> listMenu = dao.getViewModelList("get_user_menu",Menu.class,new Object[]{userId});
//        List<MenuTreeNode> nodes = toTreeNodeList(listMenu);
//        MenuTreeNode menuTreeNode = this.listToTreeNode("0", nodes);
//        return Response.success(Optional.ofNullable(menuTreeNode).orElseGet(MenuTreeNode::new));
//    }

    /**
     * 复制集合
     * @param list
     * @return
     */
    private List<MenuTreeNode> toTreeNodeList(List<Menu> list) {
        List<MenuTreeNode> array = new ArrayList<>();

        try {
            for (Menu entity : list) {
                MenuTreeNode node = MenuTreeNode.class.newInstance();
                /** 拷贝*/
                BeanUtils.copyProperties(entity, node);

                node.setId(entity.getSysMenuId());
                node.setParentId(entity.getSysMenuParentId());
                node.setMenu(entity.getLinkUrl());
                array.add(node);
            }
        }catch (Exception ex){
            log.error("",ex);
        }

        return array;
    }




    /**
     * 修改密码
     *
     * @param oldPassword
     * @param password
     * @return
     */
    @Override
    public boolean editPassword(String oldPassword, String password) {
        User user = dao.getEntity(sessionHelper.getSessionUserId());
        if(user == null){
            throw new ServiceException(SystemCode.AccountNotExist);
        }

        try {
            URL resource = ResourceUtils.getURL("classpath:privateKey.key");
            BufferedReader br = new BufferedReader(new InputStreamReader(resource.openStream()));
            String privateKey = br.readLine();
            password = RSAUtil.decryptBase64(password,privateKey);

            oldPassword =  RSAUtil.decryptBase64(oldPassword,privateKey);
        }catch (Exception ex){
            throw new ServiceException(SystemCode.PasswordResetFail);
        }

        String pwd = user.getPassword();
        DesEncrypter des = new DesEncrypter(DesEncrypter.CD_KEY);
        String pwd2 = des.decrypt(pwd);
        if(!oldPassword.equals(pwd2)){
            throw new ServiceException(SystemCode.OldPasswordError);
        }

        user.setPassword(des.encrypt(password));
        return dao.update(user);
    }

    /**
     * 修改个人资料
     *
     * @param userDTO
     * @return
     */
    @Override
    public boolean editUserInfo(UserDTO userDTO) {
        User user = dao.getEntity(sessionHelper.getSessionUserId());
        if(user == null){
            throw new ServiceException(SystemCode.AccountNotExist);
        }
        user.setEmail(userDTO.getEmail());
        user.setAvatar(userDTO.getAvatar());
        user.setUserName(userDTO.getUserName());
        user.setMobile(userDTO.getMobile());
        user.setSex(userDTO.getSex());
        return dao.update(user);
    }
}
